#include <iostream>
#include <jsoncpp/json/json.h>
#include <string>
#include <sstream>
#include <memory>

int main()
{
    /* 序列化 */
    std::string name = "zhangsan";
    int age = 20;
    int scores[] = {80, 90, 100};
    // 给数据对象类添加数据
    Json::Value value;
    value["name"] = name;
    value["age"] = age;
    value["score"].append(scores[0]);
    value["score"].append(scores[1]);
    value["score"].append(scores[2]);
    // 序列化类
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    std::stringstream sout;
    sw->write(value, &sout);        // 注意这里是指针
    std::string s = sout.str();
    printf("序列化结果:\n %s\n%s\n", s.c_str(), "========================================");

    /* 反序列化, 将s反序列化*/
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    Json::Value oValue;
    std::string errs;
    bool ret = cr->parse(s.c_str(), s.c_str() + s.size(), &oValue, &errs);
    if(ret == 0) {
        std::cerr << "somethin wrong: " << errs << std::endl;
        return -1;
    } else {
        printf("反序列化结果: \nname: %s\nage: %d\n", 
            (oValue["name"].asString()).c_str(), oValue["age"].asInt());
        for(int i = 0; i < 3; ++i) {
            printf("成绩%d: %d\n", i, oValue["score"][i].asInt());
        }
    }
    return 0;
}